<!-- 产品发布 - 基础设置 -->
<template>
  <el-form
    ref="formRef"
    :disabled="props.isDetail"
    :model="formData"
    :rules="rules"
    label-width="100px"
  >
    <el-form-item label="产品名称" prop="name">
      <el-input
        v-model="formData!.name"
        :autosize="{ minRows: 2, maxRows: 2 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="64"
        placeholder="请输入产品名称"
        type="textarea"
      />
    </el-form-item>
    <el-form-item prop="platformCategoryId" :title="formData!.type">
      <template #label>
        <Tooltip title="行业类目" message="这是平台预设的行业类目，用于全平台所有商家的产品筛选" />
      </template>
      <el-cascader
        v-model="formData!.platformCategoryId"
        :options="platformCategoryTree"
        :props="defaultProps"
        class="w-80"
        :filterable="false"
        :clearable="true"
        node-key="id"
        :placeholder="platformCategoryLoading ? '数据加载中' : '请选择行业类目'"
      />
    </el-form-item>
    <el-form-item prop="categoryId">
      <template #label>
        <Tooltip title="产品分类" message="这是店铺自己的产品分类，用于商家自己名下的产品筛选" />
      </template>
      <el-cascader
        v-model="formData!.categoryId"
        :options="categoryTree"
        :props="defaultProps"
        class="w-80"
        :filterable="false"
        :clearable="true"
        node-key="id"
        :placeholder="categoryLoading ? '数据加载中' : '请选择产品分类'"
      />
      <div class="ml-[10px] w-[60px] flex items-center justify-between">
        <el-text class="cursor-pointer" type="primary" @click="getCategoryTree()">刷新</el-text>
        <el-text
          class="cursor-pointer"
          type="primary"
          @click="goodsCategoryAddEvent()"
          v-hasRole="['shop_admin']"
          >添加
        </el-text>
      </div>
    </el-form-item>
    <!-- <el-form-item label="品牌" prop="brandId">
      <el-select v-model="formData.brandId" class="w-80" placeholder="请选择品牌" clearable>
        <el-option key="0" label="无" value="0" />
        <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
    </el-form-item> -->
    <!-- <el-form-item v-if="formData.type == 'mall'" label="关键字" prop="keyword">
      <el-input v-model="formData.keyword" class="w-80!" placeholder="请输入产品关键字" />
    </el-form-item> -->
    <!-- <el-form-item v-if="formData.type == 'mall'" label="产品简介" prop="introduction">
      <el-input
        v-model="formData.introduction"
        :autosize="{ minRows: 2, maxRows: 6 }"
        :clearable="true"
        :show-word-limit="true"
        class="w-80!"
        maxlength="128"
        placeholder="请输入产品简介"
        type="textarea"
      />
    </el-form-item> -->
    <el-form-item label="封面图" prop="picUrl">
      <UploadImg v-model="formData!.picUrl" :disabled="props.isDetail" />
      <div class="ml-5px">
        <el-text type="info">建议尺寸：800x800</el-text>
      </div>
    </el-form-item>
    <el-form-item label="轮播图" prop="sliderPicUrls">
      <UploadImgs v-model="formData!.sliderPicUrls" :disabled="props.isDetail" />
      <div class="ml-5px">
        <el-text type="info">建议尺寸：800x800</el-text>
      </div>
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
// import {PropType, Ref} from 'vue'
// import {copyValueToTarget} from '@/utils'
import { propTypes } from '@/utils/propTypes'
import { defaultProps, handleTree } from '@/utils/tree'
import type { Spu } from '@/api/mall/product/spu'
import { ShopCategoryApi } from '@/api/mall/shop/category'
import * as ProductCategoryApi from '@/api/mall/product/category'
// import * as ProductBrandApi from '@/api/mall/product/brand'
import { useShopStore } from '@/store/modules/shop'

defineOptions({ name: 'ProductSpuInfoForm' })

const props = defineProps({
  // propFormData: {
  //   type: Object as PropType<Spu>,
  //   default: () => {
  //   }
  // },
  activeName: propTypes.string.def(''),
  isDetail: propTypes.bool.def(false) // 是否作为详情组件
})

const message = useMessage() // 消息弹窗
const shopStore = useShopStore()

const formRef = ref() // 表单 Ref
const formData = defineModel<Spu>({}) // 表单数据
const rules = reactive({
  name: [required],
  platformCategoryId: [required],
  categoryId: [required],
  //keyword: [required],
  //introduction: [required],
  picUrl: [required]
  //sliderPicUrls: [required],
  //brandId: [required]
})

// /** 将传进来的值赋值给 formData */
// watch(
//   () => props.propFormData,
//   (data) => {
//     if (!data) {
//       return
//     }
//     copyValueToTarget(formData.value, data)
//   },
//   {
//     immediate: true
//   }
// )
watch(
  () => formData.value!.shopId,
  (data) => {
    if (!data) {
      return
    }
    getPlatformCategoryTree()
  }
)
watch(
  () => formData.value!.type,
  (data) => {
    if (!data) {
      return
    }
    getCategoryTree()
  }
)

/** 表单校验 */
const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
    // // 校验通过更新数据
    // Object.assign(props.propFormData, formData.value)
  } catch (e) {
    message.error('【基础设置】不完善，请填写相关信息')
    emit('update:activeName', 'info')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

/** 初始化 */
onMounted(() => {
  //getBrandList()
  getPlatformCategoryTree()
  getCategoryTree()
})

// const brandList = ref<any>([]) // 品牌列表
// const getBrandList = async () => {
//   brandList.value = await ProductBrandApi.getSimpleBrandList()
// }

const platformCategoryLoading = ref(true)
const platformCategoryList = ref<any>([])
const platformCategoryTree = ref<any>([])
const getPlatformCategoryTree = async () => {
  let shopId = formData.value!.shopId || ''
  if (!shopId) {
    await shopStore.setShopInfoAction()
    shopId = shopStore.shopInfo?.id
  }
  if (!shopId) {
    return
  }
  platformCategoryLoading.value = true
  platformCategoryList.value = await ShopCategoryApi.getShopCategorySimpleList(shopId)
  platformCategoryTree.value = handleTree(platformCategoryList.value, 'id')
  platformCategoryLoading.value = false
}

const categoryLoading = ref(true)
const categoryTree = ref<any>([])
const getCategoryTree = async () => {
  let shopId = formData.value!.shopId || ''
  if (!shopId) {
    await shopStore.setShopInfoAction()
    shopId = shopStore.shopInfo?.id
  }
  if (!shopId) {
    return
  }
  categoryLoading.value = true
  const data = await ProductCategoryApi.getCategorySimpleList(shopId)
  categoryTree.value = handleTree(data, 'id')
  categoryLoading.value = false
}

const router = useRouter()
const goodsCategoryAddEvent = () => {
  //window.open(router.resolve({ path: '/product/category' }).href)
  router.push({ name: 'ProductCategory' })
}
</script>
